<template>
  <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" size="medium">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="出库单号" prop="code">
          <el-input v-model="ruleForm.code" placeholder="可不填写，自动生成" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="*出库单类型" prop="stId">
          <el-select v-model="ruleForm.stId" placeholder="请选择出库类别" clearable>
            <el-option label="销售出库" value="1"></el-option>
            <el-option label="调拨出库" value="2"></el-option>
            <el-option label="其它出库" value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="关联订单号" prop="associatedOrderNumber">
          <el-input v-model="ruleForm.associatedOrderNumber" placeholder="" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="*客户编号" prop="customerId">
          <el-input v-model="ruleForm.customerId" placeholder="请输入关键词搜索或者双击选择" @dblclick="openCustomerDialog" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="*客户名称" prop="customerName">
          <el-input v-model="ruleForm.customerName" placeholder="" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="客户联系人" prop="customerContacts">
          <el-input v-model="ruleForm.customerContacts" placeholder="" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="*客户联系方式" prop="customerPhone">
          <el-input v-model="ruleForm.customerPhone" placeholder="" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="制单人" prop="preparedName">
          <el-input v-model="ruleForm.preparedName" placeholder="" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="制单时间" prop="preparedTime">
          <el-date-picker v-model="ruleForm.preparedTime" type="date" placeholder="选择制单时间" value-format="YYYY-MM-DD" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-form-item label="备注" prop="remark">
          <el-input v-model="ruleForm.remark" type="textarea" placeholder="请输入备注信息" :maxlength="300" show-word-limit />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24" style="text-align: right;">
        <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
      </el-col>
    </el-row>
  </el-form>

  <!-- 客户选择弹窗 -->
  <el-dialog v-model="dialogVisible" title="选择客户" width="600px">
    <el-table :data="customerList" style="width: 100%" @row-dblclick="handleCustomerSelect">
      <el-table-column prop="customerCode" label="客户编号" width="120" />
      <el-table-column prop="customerName" label="客户名称" />
      <el-table-column prop="customerContact" label="联系人" />
      <el-table-column prop="customerTel" label="联系方式" />
      <el-table-column label="操作" width="80">
        <template #default="scope">
          <el-button size="small" @click="handleCustomerSelect(scope.row)">选择</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>

  <el-table :data="tableData" border style="width: 100%; margin-bottom: 20px;">
    <el-table-column prop="associatedOrderNumber" label="订单号" width="130" />
    <el-table-column prop="productCode" label="产品编码" width="130"/>
    <el-table-column prop="productName" label="产品名称" width="130" />
    <el-table-column prop="specifications" label="规格"  width="130" />
    <el-table-column prop="bacth" label="批次" width="130" />
    <el-table-column prop="price" label="单价" width="130" />
    
    <el-table-column prop="incomingQuantity" label="出库数量" width="130" />
    <el-table-column label="总价格" width="130">
  <template #default="scope">
    {{ (Number(scope.row.price) * Number(scope.row.outgoingQuantity)).toFixed(2) }}
  </template>
</el-table-column>
    <el-table-column prop="customerName" label="客户名称" width="130" />
    <el-table-column prop="locationName" label="库位名称" width="130" />
    <el-table-column label="操作" width="100">
      <template #default="scope">
        <el-button type="text" @click="removeProduct(scope.$index)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-button type="primary" @click="addProduct()">新增产品
    <el-dialog v-model="dialogVisibles" title="新增产品" width="500">
      <!-- 产品选择表格 -->
      <el-table :data="productList" style="width: 100%" @row-dblclick="">
        <el-table-column prop="productCode" label="产品编码" width="120" />
        <el-table-column prop="productName" label="产品名称" />
        <el-table-column prop="specifications" label="规格" />
        <el-table-column prop="stockQuantity" label="库存数量" />
        <el-table-column label="操作" width="80">
          <template #default="scope">
           
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </el-button>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import http from '@/http/axiosHelper'

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  code: '',
  stId: '',
  batch: '2025-7-25',
  associatedOrderNumber: '',
  customerId: '',
  customerName: '',
  customerContacts: '',
  customerPhone: '',
  preparedName: '',
  preparedTime: '',
  remark: '',
  stateRc: 0 // 0表示出库
})

//产品显示列表
const page = ref({
  PageIndex: 1,
  PageSize: 10,
  pageCount: 0,
  totaCount: 0,
})
const tableData = ref([]);
const customerList = ref([]);
const productList = ref([]);

onMounted(()=>{
  tableDataData();
  CustomerListData();
  ProductListData();
})

const tableDataData = () => {
  const params: any = {
    PageIndex: page.value.PageIndex,
    PageSize: page.value.PageSize,
    stateRc: 0 
  };
  http.get("/shangyou/api/Stocking/GetProduct",{params})
  .then(res=>{
      tableData.value = res.data.pageData;
      page.value.pageCount = res.data.pageCount;
      page.value.totaCount = res.data.totaCount;
   })
}

// 获取客户列表
const CustomerListData = () => {
  http.get("/shangyou/api/Customer/GetCustomer")
    .then(res => {
      customerList.value = res.data.data
    })
}

// 获取产品列表
const ProductListData = () => {
  http.get("/shangyou/api/Product/GetProduct")
    .then(res => {
      productList.value = res.data.data
    })
}

const rules = reactive<FormRules>({

  code: [{ required: true, message: '请输入出库单号', trigger: 'blur' }],
  stId: [{ required: true, message: '请选择出库单类型', trigger: 'change' }],
  associatedOrderNumber: [{ required: true, message: '请输入关联订单号', trigger: 'blur' }],
  customerId: [{ required: true, message: '请输入客户编号', trigger: 'blur' }],
  customerName: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  customerContacts: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  customerPhone: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
  preparedName: [{ required: true, message: '请输入制单人', trigger: 'blur' }],
  preparedTime: [{ required: true, message: '请选择制单时间', trigger: 'change' }],
  remark: [{ required: false, message: '', trigger: 'blur' }]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 添加出库标识
      const submitData = {
        ...ruleForm,
        stateRc: 0 // 0表示出库
      };
      http.post("/read/api/WarehouseStoking/AddStocking", submitData)
        .then(res => {
          if (res.data.code == 200) {
            ElMessage.success("出库单创建成功！")
          } else {
            ElMessage.error("出库单创建失败！")
          }
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const dialogVisible = ref(false)
const dialogVisibles = ref(false)

const openCustomerDialog = () => {
  dialogVisible.value = true
}

const handleCustomerSelect = (row: any) => {
  ruleForm.customerId = row.customerCode
  ruleForm.customerName = row.customerName
  ruleForm.customerContacts = row.customerContact
  ruleForm.customerPhone = row.customerTel
  dialogVisible.value = false
}



onMounted(() => {
  CustomerListData();
  ProductListData();
  ruleForm.code = getOrderNo();
})

const getOrderNo = () => {
  const now = new Date();
  const pad = (n: number) => n.toString().padStart(2, '0');
  const year = now.getFullYear();
  const month = pad(now.getMonth() + 1);
  const day = pad(now.getDate());
  const hour = pad(now.getHours());
  const minute = pad(now.getMinutes());
  const second = pad(now.getSeconds());
  return `CK${year}${month}${day}${hour}${minute}${second}`; // CK表示出库
}

const addProduct = () => {
  dialogVisibles.value = true
}

const removeProduct = (index: number) => {
  tableData.value.splice(index, 1)
}

const selectLocation = (row: any) => {
  row.location = '选中库位'
}
</script>